package org.liaohailong.helloworld.study;

/**
 * Author: liaohailong
 * Time: 2021/5/8 16:56
 * Describe:
 */
public class MinStack {
    Node head;
    Node foot;

    /**
     * initialize your data structure here.
     */
    public MinStack() {

    }

    public void push(int val) {
        Node node = new Node();
        node.val = val;
        if (head == null) {
            node.min = val;
            head = node;
            foot = head;
        } else {
            Node temp = head;
            node.next = head;
            head = node;
            temp.preview = head;
            node.min = Math.min(temp.min, val);
        }
    }

    public void pop() {
        if (isEmpty()) {
            return;
        }
        if (head == foot) {
            head = null;
            foot = null;
        } else {
            head = head.next;
        }
    }

    public int top() {
        if (isEmpty()) {
            return -1;
        }
        return head.val;
    }

    public int getMin() {
        if (isEmpty()) {
            return -1;
        }
        return head.min;
    }

    private boolean isEmpty() {
        return foot == null || head == null;
    }

    private static final class Node {
        int val;
        Node preview;
        Node next;
        int min;
    }
}
